package com.xxxx.myproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.xxxx.myproject.entity.LoginUser;
import com.xxxx.myproject.entity.Role;
import com.xxxx.myproject.entity.User;
import com.xxxx.myproject.entity.UserRole;
import com.xxxx.myproject.mapper.RoleMapper;
import com.xxxx.myproject.mapper.RoleMenuMapper;
import com.xxxx.myproject.mapper.UserMapper;
import com.xxxx.myproject.mapper.UserRoleMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("1---进入到自定义的登录查询方法");
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, username));
        System.out.println("查询到用户 : " + user);
        Assert.notNull(user,"账号错误");
        List<String> userAuthority = getUserAuthority(user.getId());
        return new LoginUser(user,userAuthority);
    }

    public List<String> getUserAuthority(Long userId){
        List<UserRole> userRoles = userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));
        Set<Long> roleIdSet = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        List<Role> roles = roleMapper.selectBatchIds(roleIdSet);
        return roles.stream().map(Role::getRoleKey).toList();
    }

}
